package com.onlyyou.cart.service.Impl;

import com.onlyyou.cart.entity.Cart;
import com.onlyyou.cart.enums.ResultEnum;
import com.onlyyou.cart.exception.CartException;
import com.onlyyou.cart.mapper.CartMapper;
import com.onlyyou.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 小野
 * @Date: 2020/1/15 9:39
 * 购物车数据操作业务层
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public Integer rows() {
        return cartMapper.rows();
    }

    @Override
    public Map<String,Object> findAll(Integer page, Integer limit) {
        Map<String,Object> map = new HashMap<>();
        if (page<0)
            page=1;
        if (limit>rows())
            limit=rows();
        List<Cart> carts = cartMapper.findAll(page, limit);
        if (null==carts||carts.isEmpty()){
            map.put("code",1);
            map.put("status",false);
            map.put("msg","空空如也");
            map.put("data",null);
            return map;
        }
        map.put("code",0);
        map.put("status",true);
        map.put("msg","");
        map.put("data",carts);
        return map;
    }

    @Override
    public List<Cart> findByUserId(Cart cart) {
        Long userId = cart.getUserId();
        if (null==userId)
            throw new CartException(ResultEnum.NULL);
        List<Cart> carts = cartMapper.findByUserId(cart);
        if (null==carts || carts.isEmpty())
            throw new CartException(ResultEnum.NULL);
        return carts;
    }

    @Override
    @Transactional
    public Cart save(Cart cart) {
        cartMapper.save(cart);
        Cart cartId = cartMapper.findById(cart.getId());
        if (null==cartId)
            throw new CartException(ResultEnum.NULL);
        return cartId;
    }

    @Override
    @Transactional
    public Cart update(Cart cart) {
        Cart cartId = cartMapper.findById(cart.getId());
        if (null==cartId)
            throw new CartException(ResultEnum.NULL);
        cartMapper.update(cart);
        Cart cartIdUpdate = cartMapper.findById(cart.getId());
        return cartIdUpdate;
    }

    @Override
    @Transactional
    public void delete(Cart cart) {
        Cart cartId = cartMapper.findById(cart.getId());
        if (null==cartId)
            throw new CartException(ResultEnum.NULL);
        cartMapper.delete(cart);
    }
}
